<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { lessonListService, addLessonService, updateLessonService, deleteLessonService, showDetailsService} from '@/api/lesson.js'
import { coachListService } from '@/api/coach.js'

//课程数据模型
const lessons = ref([{
    "id": 1,
    "name": "增肌",
    "begin": "2023-09-21 15:00:00",
    "time": "60",
    "coachId": 1,
}])
//分页条数据模型
const page = ref(1)//当前页
const total = ref(1)//总条数
const pageSize = ref(10)//每页条数
//调用后台接口，完成课程列表查询
const lessonList = async () => {
    let params = {
        page: page.value,
        pageSize: pageSize.value,
    }
    let result = await lessonListService(params);
    //渲染视图
    total.value = result.data.total
    lessons.value = result.data.records
}
lessonList();

//当每页条数发生了变化，调用此函数
const handleSizeChange = (size) => {
    pageSize.value = size
    lessonList();
}
//当前页码发生变化，调用此函数
const handleCurrentChange = (num) => {
    page.value = num
    lessonList();
}
//教练分类模型
const coach = ref({
    "id": 1,
    "name": "教练1"
})
//教练数据回写
const coachList = async () => {
    let params = {
        page: page.value,
        pageSize: pageSize.value,
    }
    let result = await coachListService(params);
    coach.value = result.data.records
}
coachList();

//添加、修改课程表单模型
const lessonForm = ref({
    name: '',
    begin: '',
    time: '',
    coachId: ''
})
//添加、修改会员的表单校验模型
const Rules = ref({
    name: [
        { required: true, message: '请输入课程名称', trigger: 'blur' }
    ],
    begin: [
        { required: true, message: '请选择', trigger: 'blur' }
    ],
    time: [
        { required: true, message: '请输入课程时长', trigger: 'blur' }
    ],
    coachId: [
        { required: true, message: '请选择', trigger: 'blur' }
    ],
})
//默认不显示抽屉
const visibleDrawer = ref(false)
//为抽屉添加响应数据
const addLessonRef = ref()
//后台调用添加课程接口
const onAdd = async () => {
    //点击添加按钮后再进行二次校验
    await addLessonRef.value?.validate().catch((err) => { ElMessage.error("校验失败"); return Promise.reject(err) })
    let result = await addLessonService(lessonForm.value);
    ElMessage.success(result.msg ? result.msg : '添加成功')
    //让抽屉消失
    visibleDrawer.value = false
    //刷新列表
    lessonList();
}
//刷新抽屉表单
const clearLessonForm = () => {
    lessonForm.value = {
        name: '',
        begin: '',
        time: '',
        coachId: '',
    }
}
//取消添加
const cancelDrawer = () => {
    visibleDrawer.value = false
}


//默认不显示对话框
const visibleDialog = ref(false)
//展示编辑对话框弹窗
const showDialog = (row) => {
    clearLessonForm()
    visibleDialog.value = true
    //给编辑框回写原先信息
    lessonForm.value.name = row.name
    lessonForm.value.begin = row.begin
    lessonForm.value.time = row.time
    lessonForm.value.coachId = row.coachId
    //扩展模型添加id
    lessonForm.value.id = row.id
}
//为对话框添加响应数据
const updateLessonRef = ref()
//后台调用修改会员接口
const onUpdate = async () => {
    //点击修改后再进行二次校验
    await updateLessonRef.value?.validate().catch((err) => { ElMessage.error("校验失败"); return Promise.reject(err) })
    let result = await updateLessonService(lessonForm.value);
    ElMessage.success(result.msg ? result.msg : '修改成功')
    //让对话框消失
    visibleDialog.value = false
    //刷新列表
    lessonList();
}

//取消修改
const cancelDialog = () => {
    visibleDialog.value = false
}

const deleteLesson = (row) => {
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result = await deleteLessonService(row.id);
            ElMessage({
                type: 'success',
                message: result.msg ? result.msg : '删除成功',
            })
            lessonList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
//默认不显示详细信息框
const detailsDialog = ref(false);
const details = ref({
    "coachName": "",
    "memberName": [],
})
//显示课程的详细信息（包括课程教练和报名的会员）
const showDetails = async (row) => {
    detailsDialog.value = true;
    let result = await showDetailsService(row.id)
    details.value = result.data
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>课程管理</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer = true; clearLessonForm()">添加课程</el-button>
                </div>
            </div>
        </template>
        <!-- 会员列表 -->
        <el-table :data="lessons" style="width: 100%">
            <el-table-column label="序号" width="100">
                <template v-slot="scope">
                    <!-- 序号实现自动增加且连续 -->
                    {{ (page - 1) * pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="课程名称" prop="name" width="200"></el-table-column>
            <el-table-column label="开课时间" prop="begin" width="200"></el-table-column>
            <el-table-column label="课程时长/min" prop="time" width="250"></el-table-column>
            <el-table-column label="其它" prop="time" width="200">
                <template #default="{ row }">
                    <el-button type="info" @click="showDetails(row)">课程详细信息</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteLesson(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" background
            layout="sizes,prev, pager,next,jumper,total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :total="total">
        </el-pagination>

        <!-- 抽屉中嵌套添加表单 -->
        <el-drawer v-model="visibleDrawer" title="添加课程" direction="rtl">
            <div>
                <el-form ref="addLessonRef" :model="lessonForm" :rules="Rules">
                    <el-form-item label="课程名称" prop="name">
                        <el-input v-model="lessonForm.name" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="开课时间" prop="begin">
                        <el-input type="datetime-local" v-model="lessonForm.begin" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="课程时长/min" prop="time">
                        <el-input type="number" v-model="lessonForm.time" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="课程教练：" prop="coachId">
                        <el-select placeholder="请选择" v-model="lessonForm.coachId">
                            <el-option v-for="c in coach" :key="c.id" :label="c.name" :value="c.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                </el-form>
                <!-- 按钮设置 -->
                <div>
                    <el-button @click="cancelDrawer(); clearLessonForm()">取消</el-button>
                    <el-button type="primary" @click="onAdd">
                        添加
                    </el-button>
                </div>
            </div>
        </el-drawer>

        <!-- 对话框嵌套编辑表单 -->
        <el-dialog v-model="visibleDialog" title="修改课程">
            <div>
                <el-form ref="addLessonRef" :model="lessonForm" :rules="Rules">
                    <el-form-item label="课程名称" prop="name">
                        <el-input v-model="lessonForm.name" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="开课时间" prop="begin">
                        <el-input type="datetime-local" v-model="lessonForm.begin" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="课程时长/cm" prop="time">
                        <el-input type="number" v-model="lessonForm.time" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="课程教练：" prop="coachId">
                        <el-select placeholder="请选择" v-model="lessonForm.coachId">
                            <el-option v-for="c in coach" :key="c.id" :label="c.name" :value="c.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                </el-form>
                <!-- 按钮设置 -->
                <div>
                    <el-button @click="cancelDialog(); clearLessonForm()">取消</el-button>
                    <el-button type="primary" @click="onUpdate">
                        修改
                    </el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 对话框中显示详细信息 -->
        <el-dialog v-model="detailsDialog" title="课程详细信息">
            <el-descriptions :model="details" border :column="1" >
                <el-descriptions-item label="课程教练" >{{ details.coachName }}</el-descriptions-item>
                <el-descriptions-item label="课程学员">
                    <span v-for="member in details.memberName">{{member}},</span>
                </el-descriptions-item>
            </el-descriptions>
        </el-dialog>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>